import backtrader as bt
import numpy as np
import pandas as pd
import traceback
import datetime
from indicators.bias_ind import bias_ind
from indicators.wave_index_ind import wave_index_ind
import pymysql

class MysqSM25Bias(bt.Strategy):
    # 策略参数
    params = dict(
        period=20,  # 均线周期
        look_back_days=30,
        printlog=False,
        period_ema_fast=10,
        period_ema_slow=100,
        short_window=30,
        long_window=60,
        N1=3,
        N2=50,
        N3=25,
        wave_window=20,
        wave_two_window=50,
        wave_three_window=70,
    )
    def __init__(self):
        try:
         for data in self.datas:
           # 五日移动平均线
           data.sma25 = bt.indicators.SimpleMovingAverage(data, period=25)
           data.bias24 = bias_ind(wave_window=self.p.wave_window, data=data.close)
           #bt.indicators
        except Exception as e:
            traceback.print_exc()
        #遍历所有股票,计算20日均线
        #for data in self.datas:
    def notify_order(self, order):
        """
        订单状态处理
        Arguments:
            order {object} -- 订单状态
        """
        if order.status in [order.Submitted, order.Accepted]:
            # 如订单已被处理，则不用做任何事情
            return
        # 检查订单是否完成
        if order.status in [order.Completed]:
            if order.isbuy():
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
                #print('BUY成交, 执行价={0}, {1}'.format(order.executed.price, order.executed.size))
            #elif order.issell():
                #print('SELL成交, 执行价={0}, {1}'.format(order.executed.price, order.executed.size))
            self.bar_executed = len(self)
        # 订单因为缺少资金之类的原因被拒绝执行
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
        # 订单状态处理完成，设为空
        self.order = None

    def notify_trade(self, trade):
        """
        交易成果
        Arguments:
            trade {object} -- 交易状态
        """
        if not trade.isclosed:
            return
        # 显示交易的毛利率和净利润
        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                 (trade.pnl, trade.pnlcomm), doprint=True)
    def next(self):
        #print(len(self))

        total_value = self.broker.getvalue()
        p_value = total_value*0.9/10
        for data in self.datas:
          #print(len(data)," ",data.buflen())
          if len(data) == (data.buflen()) :
            pos = self.getposition(data).size
            #data.close[0] > data.N_High[0] and
            if not pos :
                if self.getFrontB(data,  25)  :
                            #if data.close[-1] >data.close[0] and  data.close[-2] >data.close[-1] and  data.close[-3] >data.close[-2] :
                            #if data.close[-1] > data.close[0] and data.close[-2] > data.close[-1] :
                                if  data.bias24[0]-data.bias24[-1] > 3  and data.bias24[0] > data.bias24[-1] and data.low[0]<data.low[-1] :
                                      db = pymysql.connect(host='101.35.200.120', port=3306, user='root',passwd='ljf123456', db='gp', charset='utf8')
                                      cursor = db.cursor()
                                      date_p = datetime.datetime.now().date()
                                      str_p = str(date_p)
                                      selectSql = """select * from record_strategy  WHERE  code = '%s'  AND strateg_type = %s """ \
                                                  % (data._name, 2)
                                      cursor.execute(selectSql)
                                      selectResults = cursor.fetchall()
                                      if (len(selectResults) == 0):
                                          # datetime.datetime.now().year + '-' + datetime.datetime.now().month + '-' + datetime.datetime.now().day
                                          # time =date_p = datetime.datetime.now().date()
                                          sql1 = """INSERT INTO record_strategy (code,strateg_type,is_permanent,create_time) VALUES ('%s','%s','%s','%s') """ \
                                                 % (data._name, 2, 0, str_p)
                                          cursor.execute(sql1)
                                          #id = cursor.lastrowid
                                          #sql1 = """INSERT INTO record_strategy_price (strategy_id,max_price,min_price,resistance_price) VALUES ('%s','%s','%s','%s') """ \
                                          #       % (id, h.val, minData, plan)
                                          cursor.execute(sql1)
                                      db.commit()


            '''
            if pos!=0 :
                if  (data.close[0] > data.sma25[0]):
                     self.close (data = data)
            '''

    def log(self, txt, dt=None,doprint=False):
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            print(f'{dt.isoformat()},{txt}')
    #  or self.getFrontB( data, 3) == True
    def getFrontB(self, data,  end):
        for i in range(1, end):
            #print(data.sma25[-i],"",data.close[-i])
            if data.sma25[-i] < data.high[-i]:
                return False

        return True



    #记录交易收益情况（可省略，默认不输出结果）
    #def notify_trade(self,trade):
    #    if not trade.isclosed:
    #        return
    #    self.log(f'策略收益：\n毛收益 {trade.pnl:.2f}, 净收益 {trade.pnlcomm:.2f}')
